package com.sanmu.proxy;


import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @version 1.0
 * @Author xinnian
 * @Date 2024/9/30 15:33
 * @注释
 * @create: 2024-09-30 15:33
 */

public class VehicleProxyProvider {
    private Vehicle vehicle;

    public VehicleProxyProvider(Vehicle vehicle) {
        this.vehicle = vehicle;
    }
    public Vehicle getProxy() {
        //获取类加载对象
        ClassLoader classLoader = vehicle.getClass().getClassLoader();
        // 2.获取接口类型数组, 为什么是接口信息，而不是方法，是因为我们都是走接口
        //的
        Class<?>[] interfaces = vehicle.getClass().getInterfaces();
        //创建invocationHandler对象 因为他是接口所以用匿名类来实现就可以
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("交通工具开始运行了...");
                Object res = method.invoke(vehicle, objects);
                System.out.println("交通工具停止运行了...");



                return res;
            }
        };

        Vehicle proxy = (Vehicle)Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);

        return proxy;


    }

}
